<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity {
    private $_id;
    public $email;

    const ERROR_EMAIL_INVALID = 1001;
    const ERROR_BLOCKED_USER  = 1002;
    const ERROR_DELETED_USER  = 1003;
    const ERROR_UNCHECKED_USER = 1004;

    public function __construct($email, $password) {
        $this->email = $email;
        $this->password = $password;
    }

    /**
     * Authenticates a user.
     * The example implementation makes sure if the email and password
     * are both 'demo'.
     * In practical applications, this should be changed to authenticate
     * against some persistent user identity storage (e.g. database).
     * @return boolean whether authentication succeeds.
     */
    public function authenticate() {
        $user=User::model()->find('email=? AND password=?',array($this->email, md5($this->password)));
        if($user===null)
            $this->errorCode=self::ERROR_EMAIL_INVALID | self::ERROR_PASSWORD_INVALID;
        else {
            switch($user->status) {
                case User::STATUS_NORMAL:
                    $this->_id=$user->id;
                    $this->email = $user->email;
                    $this->setState('status', $user->status);
                    $this->username = $user->nickname;
                    $this->errorCode=self::ERROR_NONE;
                    break;
                case User::STATUS_BLOCKED:
                    $this->errorCode = self::ERROR_BLOCKED_USER;
                    break;
                case User::STATUS_DELETED:
                    $this->errorCode = self::ERROR_DELETED_USER;
                    break;
                case User::STATUS_UNCHECKED:
                    $this->errorCode = self::ERROR_UNCHECKED_USER;
                    break;
                default:
                    $this->errorCode = self::ERROR_UNKNOWN_IDENTITY;
                    break;
            }
        }
        return !$this->errorCode;
    }

    public function getId() {
        return $this->_id;
    }

    public function getEmail() {
        return $this->email;
    }

}